# @Time : 2020/9/8 11:19
# @Author : Fioman 
# @Phone : 13149920693
"""
给定一个整数数组 nums 和一个目标值 target，请你在该数组中找出和为目标值的那 两个 整数，并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是，数组中同一个元素不能使用两遍。

示例:
nums = [2,7,11,15]
target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
返回  [0,1]
"""
import time


class Solution(object):
    # 方法1,就是遍历整个列表,但是使用enumerate会小号很大的时间.所以这里考虑换个方式
    def twoSum01(self, nums, target):
        # 遍历列表
        for index1, x in enumerate(nums):
            for index2, y in enumerate(nums[index1 + 1:]):
                if x + y == target:
                    return [index1, index2 + index1 + 1]

    def twoSum02(self, nums, target):
        j = -1
        for i in range(len(nums)):
            temp = nums[:i]
            if (target - nums[i]) in temp:
                j = temp.index(target - nums[i])
                break
        if j >= 0:
            return [j, i]

    def twoSum03(self, nums, target):
        # 通过哈希来求解,这里通过字典来模拟哈希查询的过程.个人理解这种办法相较于方法一其实就是字典记录了num1和num2的值和位置,而节省了再查找num2的步骤.
        hashMap = {}
        for index, num in enumerate(nums):
            hashMap[num] = index

        for index, num in enumerate(num):
            j = hashMap.get(target - num)
            if j is not None and index != j:
                return [index, j]

    def twoSum04(self, nums, target):
        hashMap = {}
        for index, num in enumerate(nums):
            if hashMap.get(target - num) is not None:
                return [hashMap.get(target - num), index]
            hashMap[num] = index


if __name__ == '__main__':
    nums = [2, 7, 11, 15]
    target = 13
    s = Solution()
    start = time.time()
    res = s.twoSum02(nums, target)
    print("计算耗时: {}".format(time.time() - start))
    print(res)
